import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Browser, BrowserHrm, RouteLayout } from 'weaver-mobile-page';
import { withRouter } from 'react-router-dom';
import { createForm } from 'rc-form';
import {
  Tools,
  Button,
  Bubble,
  Icon,
  Avatar,
  InputItem,
  List,
  DatePicker,
  TextareaItem,
  Toast
} from 'weaver-mobile';
import { DateDiffDays } from '../../../util'
const ButtonGroup = RouteLayout.ButtonGroup;
const { DatePickerInput } = DatePicker;
const getLabel = Tools.getLabel;
const { FormItem } = List;

/*
新建页面
*/
@inject('planViewStore')
@withRouter
@observer
class New extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      newType: "summaryout",
      index: -1,
      itemList: [],
      layoutButtons: []
    };
    this.store = this.props.planViewStore;
  }

  componentWillMount() {
    const queryString = this.props.location.search
    let queryStr = queryString.replace("?", "");
    let type, index
    if (queryStr != '') {
      let queryArr = queryStr.split('&')
      type = queryArr[0]
      index = queryArr[1] || -1
    }
    // let type = this.props.location.state?this.props.location.state.type:''
    if (type == '') {
      type = this.props.type
    }
    this.setState({ newType: type, index }, () => {
      this.initItemList()
    })
    this.initLayoutButtons()
  }
  initLayoutButtons = () => {
    let { history } = this.props
    this.setState({
      layoutButtons: [{
        key: 'clear',
        text: getLabel(31129, '取消'),
        onClick: () => {
          // history.go(-1)
          this.props.history.push("/planHome/planView/index")
        },
      },
      {
        key: 'submit',
        text: getLabel(826, '确定'),
        onClick: () => this.save(),
        type: 'primary',
      },]
    })
  }

  componentWillReceiveProps(nextProps) {
    if (!this.state.itemList || this.state.itemList.length < 0) {
      this.initItemList()
    }
  }

  render() {
    const prefixClass = 'workrelate-mobile-plan-planview-new-';
    let { planmap, planlist } = this.store;
    let { itemList, newType } = this.state
    const { history } = this.props;
    const { getFieldProps } = this.props.form;
    let headerTitle = `${getLabel(82, '新建')}${newType == 'plan' ? getLabel('407', '计划') : getLabel('509021', '总结')}`
    return (
      // <RouteLayout>
      <div
        key="summaryout"
        className="wm-route-layout workrelate-roll workrelate-condition"
      >
        <div className={`${prefixClass}container roll`}>
          <List renderHeader={() => headerTitle}>

            {itemList &&
              itemList.map(p => {
                return this.renderByInputType(
                  p.inputtype,
                  p.fieldname,
                  p.showname,
                  p.ismust
                );
              })}

          </List>
        </div>
        <ButtonGroup data={this.state.layoutButtons} isButton={true} />
      </div>
      // </RouteLayout>

    );
  }

  onDateChange = (fieldName) => {
    let values = this.props.form.getFieldsValue()
    if (values['begindate2'] && values['enddate2']) {
      let days = DateDiffDays(values['begindate2'], values['enddate2'])
      if (days < 0) {
        Bubble.warning(getLabel(16721, '开始时间不能大于结束时间'));
        // Toast.info('开始时间不能小于结束时间', 1);
        let fields = {}
        fields[fieldName] = ''
        this.props.form.setFieldsValue(fields)
      } else {
        this.props.form.setFieldsValue({ 'days2': days })
      }
    }
    if (values['begindate1'] && values['enddate1']) {
      let days = DateDiffDays(values['begindate1'], values['enddate1'])
      if (days < 0) {
        Bubble.warning(getLabel(16721, '开始时间不能大于结束时间'));
        // Toast.info('开始时间不能小于结束时间', 1);
        let fields = {}
        fields[fieldName] = ''
        this.props.form.setFieldsValue(fields)
      } else {

        this.props.form.setFieldsValue({ 'days1': days })
      }
    }
  }

  initItemList = () => {
    let { newType } = this.state
    let itemList = []
    if (newType == 'plan') {
      itemList = this.store.planmap.list
    } else {
      itemList = this.store.summarymap.list
    }
    this.setState({ itemList })
  }


  renderByInputType = (inputType, fieldname, showname, ismust) => {
    ismust = ismust == 1;
    const { getFieldProps } = this.props.form;
    let com;
    if (inputType == 3) {
      com = (
        <List>
          <span>
          <FormItem
            label={showname}
            line
            content={(<DatePickerInput
              mode="date"
              onOk={() => { this.onDateChange(fieldname) }}
              {...getFieldProps(fieldname, {
                rules: [{ required: ismust }],
              })}
              placeholder={getLabel(18214, '请选择')}
            >
            </DatePickerInput>)}
          />
          </span>
        </List>
      );
      return com;
    } else if (inputType == 4) {
      com = (
        <InputItem
          {...getFieldProps(fieldname, {
            rules: [{ required: ismust }],
          })}
          type="number"
          placeholder={getLabel('83869', '请输入')}
          ref={el => this[fieldname] = el}
        ></InputItem>
      );
    } else if (inputType == 2) {
      com = (
        <TextareaItem
          {...getFieldProps(fieldname, {
            rules: [{ required: ismust }],
          })}
          autoHeight
          placeholder={getLabel('83869', '请输入')}
        ></TextareaItem>
      );
    } else {
      com = (
        <InputItem
          {...getFieldProps(fieldname, {
            rules: [{ required: ismust }],
          })}
          placeholder={getLabel('83869', '请输入')}
          ref={el => this[fieldname] = el}
        />
      );
    }

    return (
      <List>
      <span
        onClick={() => {
          //如果有换行的话，点击任意区域聚焦输入
          if (this[fieldname]) {
            this[fieldname].focus()
          }
        }}
      >
        <FormItem
          extra={<Icon type="editor" size="xxs" />}
          key={fieldname}
          label={showname}
          wrap="nowrap"
          required={ismust && !this.props.form.getFieldsValue()[fieldname]}
          line
          content={com}
        />
      </span>
      </List>
    );
  };

  save = () => {
    let { newType, index } = this.state
    let { summaryin, summaryout, planlist } = this.store;
    this.props.form.validateFields((error, value) => {
      if (!error) {
        if (newType == 'summaryin') {
          index > -1 ? summaryin.splice(index, 0, value) : summaryin.push(value)
        } else if (newType == 'summaryout') {
          index > -1 ? summaryout.splice(index, 0, value) : summaryout.push(value)
        } else {
          index > -1 ? planlist.splice(index, 0, value) : planlist.push(value)
        }
        this.props.history.push("/planHome/planView/index")
      } else {
        Bubble.warning(getLabel('509065', '请输入必填项'));

      }
    });
  };


}
export default createForm()(New);
